package com.keon.jianbao;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Build;

import com.keon.jianbao.api.ApiHttpClient;
import com.keon.jianbao.bean.User;
import com.keon.jianbao.bean.WXToken;
import com.keon.jianbao.util.StringUtils;
import com.keon.jianbao.util.TLog;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.PersistentCookieStore;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.protocol.HttpContext;

import java.util.Properties;

import cn.sharesdk.framework.ShareSDK;

/**
 * 全局应用程序类：用于保存和调用全局应用配置及访问网络数据
 *
 * @author 火蚁 (http://my.oschina.net/LittleDY)
 * @version 1.0
 * @created 2014-04-22
 */
public class AppContext extends Application {
    private static AppContext instance;
    private static String PREF_NAME = "auto.pref";
    private static String LAST_REFRESH_TIME = "last_refresh_time.pref";
    private static boolean sIsAtLeastGB;

    public static IWXAPI WXapi;

    static {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            sIsAtLeastGB = true;
        }
    }

    private int loginUid;

    private boolean login;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        init();
    }

    private void init() {
        TLog.DEBUG = true;

//        Fresco.initialize(this);
        initImageLoader(getApplicationContext());

        initNetWork();

        WXapi = WXAPIFactory.createWXAPI(this, null);
    }

    public static void initImageLoader(Context context) {
        // This configuration tuning is custom. You can tune every option, you may tune some of them,
        // or you can create default configuration by
        //  ImageLoaderConfiguration.createDefault(this);
        // method.
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.threadPoolSize(3);
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        config.writeDebugLogs(); // Remove for release app

        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());
    }

    private void initNetWork() {
        // 初始化网络请求
        AsyncHttpClient client = new AsyncHttpClient();

        ShareSDK.initSDK(this);

        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        client.setCookieStore(myCookieStore);
        ApiHttpClient.setHttpClient(client);
        ApiHttpClient.setCookie(ApiHttpClient.getCookie(this));
    }

    /**
     * 获得当前app运行的AppContext
     *
     * @return
     */
    public static AppContext getInstance() {
        return instance;
    }

    public static Context getContext() {
        return instance.getApplicationContext();
    }

    public static Resources getResource() {
        return instance.getResources();
    }

    public void setProperties(Properties ps) {
        AppConfig.getAppConfig(this).set(ps);
    }

    public Properties getProperties() {
        return AppConfig.getAppConfig(this).get();
    }

    public void setProperty(String key, String value) {
        AppConfig.getAppConfig(this).set(key, value);
    }

    public static String getLastRefreshTime(String key) {
        return getPreferences(LAST_REFRESH_TIME).getString(key, StringUtils.getCurTimeStr());
    }

    public static void putToLastRefreshTime(String key, String value) {
        SharedPreferences preferences = getPreferences(LAST_REFRESH_TIME);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, value);
        apply(editor);
    }

    /**
     * 放入已读文章列表中
     */
    public static void putReadedPostList(String prefFileName, String key,
                                         String value) {
        SharedPreferences preferences = getPreferences(prefFileName);
        int size = preferences.getAll().size();
        SharedPreferences.Editor editor = preferences.edit();
        if (size >= 100) {
            editor.clear();
        }
        editor.putString(key, value);
        apply(editor);
    }

    /**
     * 获取cookie时传AppConfig.CONF_COOKIE
     *
     * @param key
     * @return
     */
    public String getProperty(String key) {
        String res = AppConfig.getAppConfig(this).get(key);
        return res;
    }

    public void removeProperty(String... key) {
        AppConfig.getAppConfig(this).remove(key);
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void apply(SharedPreferences.Editor editor) {
        if (sIsAtLeastGB) {
            editor.apply();
        } else {
            editor.commit();
        }
    }

    public static void set(String key, int value) {
        SharedPreferences.Editor editor = getPreferences().edit();
        editor.putInt(key, value);
        apply(editor);
    }

    public static void set(String key, boolean value) {
        SharedPreferences.Editor editor = getPreferences().edit();
        editor.putBoolean(key, value);
        apply(editor);
    }

    public static void set(String key, String value) {
        SharedPreferences.Editor editor = getPreferences().edit();
        editor.putString(key, value);
        apply(editor);
    }

    public static boolean get(String key, boolean defValue) {
        return getPreferences().getBoolean(key, defValue);
    }

    public static String get(String key, String defValue) {
        return getPreferences().getString(key, defValue);
    }

    public static int get(String key, int defValue) {
        return getPreferences().getInt(key, defValue);
    }

    public static long get(String key, long defValue) {
        return getPreferences().getLong(key, defValue);
    }

    public static float get(String key, float defValue) {
        return getPreferences().getFloat(key, defValue);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static SharedPreferences getPreferences() {
        SharedPreferences pre = getContext().getSharedPreferences(PREF_NAME,
                Context.MODE_MULTI_PROCESS);
        return pre;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static SharedPreferences getPreferences(String prefName) {
        return getContext().getSharedPreferences(prefName,
                Context.MODE_MULTI_PROCESS);
    }


    public boolean isLogin() {
        return login;
    }

    /**
     * 用户注销
     */
    public void Logout() {
        cleanLoginInfo();
        ApiHttpClient.cleanCookie();
        this.cleanCookie();
    }

    /**
     * 清除保存的缓存
     */
    public void cleanCookie() {
        removeProperty(AppConfig.CONF_COOKIE);
    }

    /**
     * 保存登录信息
     *
     * @param user 用户信息
     */
    public static void saveUserInfo(final User user) {
        AppContext.getInstance().setProperties(new Properties() {
            {
                setProperty("user.id", String.valueOf(user.getId()));
                setProperty("user.user_mobile", user.getUser_mobile());
                if (user.getCode() != null) {
                    setProperty("user.code", user.getCode());
                }
                setProperty("user.user_address", user.getUser_address());
                if (user.getUser_gender() != null) {
                    setProperty("user.user_gender", user.getUser_gender());
                }
                setProperty("user.user_face", String.valueOf(user.getUser_face()));
                setProperty("user.user_hobby", String.valueOf(user.getUser_hobby()));
                if (user.getUser_name() != null) {
                    setProperty("user.user_name", String.valueOf(user.getUser_name()));
                } else {
                    setProperty("user.user_name", String.valueOf(user.getUser_mobile()));
                }

            }
        });
    }

    public static void saveCookies(Header[] headers) {
        if (headers[6].getValue().contains("PHPSESSID")) {
            AppContext.getInstance().setProperty("user.sessionid", headers[6].getValue().substring(10, 36));
        }

        AsyncHttpClient client = ApiHttpClient.getHttpClient();
        HttpContext httpContext = client.getHttpContext();
        CookieStore cookies = (CookieStore) httpContext
                .getAttribute(ClientContext.COOKIE_STORE);
        if (cookies != null) {
            String tmpcookies = "";
            for (Cookie c : cookies.getCookies()) {
                tmpcookies += (c.getName() + "=" + c.getValue()) + ";";
            }
            AppContext.getInstance().setProperty(AppConfig.CONF_COOKIE,
                    tmpcookies);
            ApiHttpClient.setCookie(ApiHttpClient.getCookie(AppContext
                    .getInstance()));
        }
    }

    /**
     * 清除登录信息
     */
    public void cleanLoginInfo() {
        this.loginUid = 0;
        this.login = false;
        removeProperty("user.id", "user.code", "user.user_address", "user.user_face",
                "user.user_hobby", "user.user_name");
    }

    public static boolean tokenError(int status) {
        if (status == -1 || status == -2) {
            return true;
        }
        return false;
    }

    public static void saveWX(final WXToken wxToken) {
        AppContext.getInstance().setProperties(new Properties() {
            {
                setProperty("wx.openid", String.valueOf(wxToken.getOpenid()));
                setProperty("wx.access_token", wxToken.getAccess_token());
                setProperty("wx.refresh_token", wxToken.getRefresh_token());
            }
        });
    }

/*    public static void saveWX(final Oauth2AccessToken accessToken) {
        AppContext.getInstance().setProperties(new Properties() {
            {
                setProperty("weibo.openid", String.valueOf(accessToken.getUid()));
                setProperty("weibo.access_token", accessToken.getToken());
                setProperty("weibo.refresh_token", accessToken.getRefreshToken());
            }
        });
    }*/

    /**
     * 　　* 获取版本号
     * 　　* @return 当前应用的版本号
     */
    public int getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }
}
